#!/usr/bin/sh
echo "= ====================================================="
echo "=  Token processor by Alexey Prey Mulyukin (c) 2016"
echo "=          EMail: alexprey@yandex.ru"
echo "=    sdCloud project (http://sdcloud.io)"
echo "= ====================================================="

# Directory which used for search token files
START_DIR="$1"
# Configuration file or '--env--' if 
# configuration is stored in env variables
CONFIG_FILE="$2"
# Token files suffix which used for search token files
TOKEN_FILE_SUFFIX=".token."

TMP_SED_FILE="$START_DIR/tokens.sed"
TMP_NOT_FOUND_TOKENS="$START_DIR/tokens.null"

TMP_ENV_CONFIG_FILE="/tmp/sdCloud_deployment.conf"

if [ -z $START_DIR -a -z $CONFIG_FILE ]; then
    echo "Usage: sh replaceTokenFiles.sh START_DIR CONFIG_FILE"
    echo ""
    echo "    START_DIR - directory for search a token files"
    echo "    CONFIG_FILE - file with token configurations"
    exit 1
fi

# Validate START_DIR parameter
if [ ! -d $START_DIR ]; then
    echo "Can't access to directory '$START_DIR'"
    echo "Directory should exists!"
    exit 1
fi

# Validate CONFIG_FILE parameter
if [ ! -r $CONFIG_FILE ]; then
    if [[ "$CONFIG_FILE" == "--env--" ]]; then
        echo " Deployment configuration will be taken from environment variables"
        echo "# Automatically generated config file" > $TMP_ENV_CONFIG_FILE
        env | grep "SDCloud" >> $TMP_ENV_CONFIG_FILE
        CONFIG_FILE=$TMP_ENV_CONFIG_FILE
    else
        echo "Can't read a '$CONFIG_FILE'"
        echo "The config file should exists and be readable!"
        exit 1
    fi
fi

echo " * Target configuration file is: '$CONFIG_FILE'"
echo " * Base directory for token files search: '$START_DIR'"
echo " * Token files search filter: '*$TOKEN_FILE_SUFFIX*'"

rm -f $TMP_NOT_FOUND_TOKENS

echo " * Start token processing"

for TOKEN_FILE in `find $START_DIR -type f -name "*$TOKEN_FILE_SUFFIX*"`
do
    TARGET_FILE=`echo $TOKEN_FILE | sed "s/$TOKEN_FILE_SUFFIX/./g"`
    echo "    Start token processing for '${TOKEN_FILE#$START_DIR}' -> '${TARGET_FILE#$START_DIR}'"

    # Generate commands for SED utility and save its to temporary file
    cat $CONFIG_FILE | grep ^[^#][^=]*=.*$ | sed 's/\//\\\//g' | sed 's/^\([^#][^=]*\)=\(.*\)$/s\/__(\1)__\/\2\/g/' > $TMP_SED_FILE

    # Replace tokens
    sed -f $TMP_SED_FILE $TOKEN_FILE > $TARGET_FILE

    # Check file for not replaced tokens
    cat $TARGET_FILE | grep -o __\([^\)]\*\)__ | sed 's/__(\([^)]*\))__/\1/' | sed '/./!d' >> $TMP_NOT_FOUND_TOKENS
done

echo " * Token processing complete"

if [ -s $TMP_NOT_FOUND_TOKENS ]; then
    echo " * List of not found tokens in '$CONFIG_FILE'"
    cat $TMP_NOT_FOUND_TOKENS | sort -u
fi

# Remove temporary script with SED commands
rm -f $TMP_SED_FILE
rm -f $TMP_NOT_FOUND_TOKENS
